import functools
import json
import logging
import traceback
from time import strptime, mktime, strftime
import time
import datetime

from flask import jsonify, request
from app.response import ResponseError
from urllib.parse import unquote


class Route:
    def __init__(self, name):
        self.logger = logging.getLogger(name)
        print(self.logger)

    def try_catch(self, fn):
        @functools.wraps(fn)
        def wrapper():

            print(str(strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))
            self.logger.info('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^::' + fn.__name__)
            try:
                resp = fn()
            except Exception as e:
                print(e)
                if isinstance(e, ResponseError):
                    # print(e.message())
                    return jsonify({
                        'code': 1,
                        'msg': str(e)
                    })

                traceback.print_exc()
                # self.logger.exception(e)
                resp = jsonify({
                    'code': 1
                })
            resp.headers["Access-Control-Allow-Credentials"] = "true"
            resp.headers['Access-Control-Allow-Origin'] = '*'
            return resp

        return wrapper

    def websocket_wrapper(self, fn):
        @functools.wraps(fn)
        def wrapper(*args):
            print(str(strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))
            self.logger.info('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^:' + fn.__name__)
            res = fn(*args)

            return res

        return wrapper

    def mtk_wrapper(self, fn):
        @functools.wraps(fn)
        def wrapper():
            print(str(strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))
            self.logger.info('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^:' + fn.__name__)
            json_str = request.args.get('r', '')

            try:
                if json_str:
                    json_str = unquote(json_str)
                    data = json_str.split('*')
                else:
                    data = []
                res = fn(data)
                return res
            except Exception as e:
                traceback.print_exc()

                if isinstance(e, ResponseError):
                    return jsonify({
                        'code': 1,
                        'msg': str(e)
                    })
                else:
                    return jsonify({
                        'code': 1,
                        'msg': str(e)
                    })

        return wrapper

    def android_wrapper(self, fn):
        @functools.wraps(fn)
        def wrapper():
            print(str(strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))
            self.logger.info('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^:' + fn.__name__)
            json_str = request.args.get('r', '')
            device_id = request.args.get('d', '')
            try:
                if json_str:
                    json_str = unquote(json_str)
                    data = json.loads(json_str)
                else:
                    data = []
                res = fn(device_id, data)
                return res
            except Exception as e:
                traceback.print_exc()

                if isinstance(e, ResponseError):
                    return jsonify({
                        'code': 1,
                        'msg': str(e)
                    })
                else:
                    return jsonify({
                        'code': 1,
                        'msg': str(e)
                    })

        return wrapper

    @staticmethod
    def get_router_saver_key(router_name):
        return 'route_' + router_name
